package com.example.miaoshademo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.Date;

/**
 * @author Shenluw
 * created：2019/7/17 21:14
 */
@RestController
@Validated
public class MiaoshaController {

	private final static Logger log = LoggerFactory.getLogger(MiaoshaController.class);

	@Autowired
	private GoodsRepository goodsRepository;
	@Autowired
	private MiaoshaService  miaoshaService;

	@Autowired
	private MiaoshaOrderService miaoshaOrderService;

	@RequestMapping("/miaosha/create")
	public R createMiaosha(@NotBlank String name, @Positive Integer stock, @NotNull @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") Date startTime) {

		Goods goods = new Goods();
		goods.setName(name);
		goods.setStock(stock);
		// 简易操作 直接在创建秒杀的时候创建了 商品和库存，并且直接锁定了库存
		goods.setLockStock(stock);

		goodsRepository.save(goods);

		MiaoshaData data = miaoshaService.create(goods.getId(), stock, startTime);
		return new R(Constants.CODE_SUCCESS, "success", data);
	}

	@RequestMapping("/miaosha")
	public R miaosha(@Positive Integer uid, @Positive Integer miaoshaId) {
		log.info("before miaosha： {}:{}", uid, miaoshaId);

		// 限流  先不做 RateLimiter
		// 筛选 uid 先不做
		// 验证库存
		int result = miaoshaService.miaosh(miaoshaId, uid);

		if (result == Constants.MIAOSHA_SUCCESS) {
			// 创建订单
			MiaoshaOrder order = miaoshaService.createOrder(miaoshaId, uid);
			if (order == null) {
				log.info("after miaosha: order create error");
				return new R(Constants.CODE_ERROR, "发生了不可预料的问题导致了失败");
			}
			log.info("after miaosha: success: {}", order.getOrderId());
			return new R(Constants.CODE_SUCCESS, "秒杀成功", order);

		} else {
			log.info("after miaosha: error: {}", result);
			return new R(Constants.CODE_ERROR, "秒杀失败： " + result);
		}
	}

	@GetMapping("/miaosha/query")
	public R queryMiaosha(@Positive Integer miaoshaId) {
		MiaoshaData data = miaoshaService.query(miaoshaId);
		return new R(Constants.CODE_SUCCESS, "succss", data);
	}

	@GetMapping("/miaosha/order/query")
	public R queryMiaosha(@NotBlank String orderId) {
		MiaoshaOrder order = miaoshaOrderService.query(orderId);
		if (order != null) {
			return new R(Constants.CODE_SUCCESS, "success", order);
		}
		return new R(Constants.CODE_ERROR, "not found");
	}

}
